package czk.jvm.lecture.gc;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/11/5 14:30
 */
public class InnerClassOutOfMemory {
    public static void main(String[] args) {
        //method1();
        method2();
    }

    /**
     * 此时会内存泄漏
     * Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
     * 因为会不断创建Inner对象，此时持有外部对象的额引用，jvm不能对Outer进行垃圾回收。
     */
    public static void method1() {
        // Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        List<Outer.Inner> list = new ArrayList<>();
        while (true) {
            list.add(new Outer(1000).createInner());
        }
    }
    public static void method2() {
        // Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        List<Outer.Inner2> list = new ArrayList<>();
        while (true) {
            list.add(new Outer(1000).createInner2());
        }
    }

}
